#define _CRT_SECURE_NO_WARNINGS
#include"SList.h"

void Print(STnode* phead)
{
	STnode* cur = phead;
	while (cur)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}
STnode* Buynode(STData x)
{
	STnode* newnode = (STnode*)malloc(sizeof(STnode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}
void PushFront(STnode** pphead, STData x)
{
	assert(pphead);
	STnode* newnode = Buynode(x);

	newnode->next = *pphead;
	*pphead = newnode;
}

void PushBack(STnode** pphead, STData x)
{
	//assert(*pphead);
	STnode* newnode = Buynode(x);
	STnode* tail = *pphead;
	while (tail->next != NULL)
	{
		tail = tail->next;

	}
	tail->next = newnode;

}

void PopFront(STnode** pphead)
{
	assert(*pphead);
	STnode* del = *pphead;
	*pphead = (*pphead)->next;
	free(del);
	
}
void PopBack(STnode** pphead)
{
	assert(*pphead);
	STnode* tail = *pphead;
	while (tail->next->next != NULL)
	{
		tail = tail->next;

	}
	free(tail->next);
	tail->next = NULL;
	
}

STnode* Find(STnode* phead, STData x)
{
	assert(phead);
	STnode* newnode = phead;
	while (newnode)
	{
		if (newnode->data == x)
		{
			return newnode;
		}
		newnode = newnode->next;
	}
	return NULL;
}
void Insert(STnode** pphead, STnode* pos, STData x)
{
	assert(pphead);
	assert(pos);
	STnode* prev = *pphead;
	STnode* newnode = Buynode(x);
	if (*pphead == pos)
	{
		PushFront(pphead, x);
	}
	else
	{
		while (prev->next != pos)
		{
			prev = prev->next;

		}
		prev->next = newnode;

		newnode->next = pos;
	}
	
}
void InsertAfter(STnode* pos, STData x)
{
	assert(pos);
	STnode* newnode = Buynode(x);
	newnode->next = pos->next;
	pos->next = newnode;

}

void Erase(STnode** pphead, STnode* pos)
{
	assert(*pphead);
	STnode* cur = *pphead;
	while (cur->next != pos)
	{
		cur = cur->next;

	}
	cur->next = pos->next;
	free(pos);
	pos = NULL;
}
void EraseAfter(STnode* pos)
{
	assert(pos);
	STnode* del = pos->next;
	pos->next = pos->next->next;
	free(pos->next);
	pos->next = NULL;
}
